package cc.orange.http;

import com.google.gson.Gson;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public final class MyGsonConverterFactory extends Converter.Factory {

    public static MyGsonConverterFactory create() {
        return create(new Gson());
    }


    public static MyGsonConverterFactory create(Gson gson) {
        return new MyGsonConverterFactory(gson);
    }

    private final Gson gson;

    private MyGsonConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        //返回我们自定义的Gson响应体变换器
        return new GsonResponseBodyConverter<>(gson, type);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        //返回我们自定义的Gson响应体变换器
        return new GsonResponseBodyConverter<>(gson,type);
    }

    public class GsonResponseBodyConverter<T> implements Converter<ResponseBody,T>{
        private final Gson gson;
        private final Type type;


        public GsonResponseBodyConverter(Gson gson,Type type){
            this.gson = gson;
            this.type = type;
        }
        @Override
        public T convert(ResponseBody value){
            try {

                String response = value.string();
                //先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常
                ApiResponse apiResponse = gson.fromJson(response, ApiResponse.class);
                if (null != apiResponse) {

                    if (!apiResponse.isTokenInva()) {
                        //200的时候就直接解析，不可能出现解析异常。因为我们实体基类中传入的泛型，就是数据成功时候的格式
                        return gson.fromJson(response, type);
                    }
//                else if (!apiResponse.isContentInva()) {//内容为空
////                    throw new IOException();
////                }
                    else {
//                        ZXSharedPrefUtil sh = new ZXSharedPrefUtil();
//                        sh.putBool("islogin", false);
//                        if (apiResponse.msg.equals("token验证失败")) {
//                        } else {
//                        }
                        throw new IOException();
                    }

                } else {
                    return  gson.fromJson(response, type);
                }
            } catch (Exception e) {
                return null;
            }
        }
    }
}